package zaizai.com;

import com.ajguan.ResourceTable;
import ohos.agp.components.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 模拟数据列表provider
 */
public class SimpleAdapter extends BaseItemProvider {

    /**
     * 模拟数据
     */
    private List<String> mData;


    /**
     * constructor
     */
    public SimpleAdapter() {
        mData = new ArrayList<>();
    }

    @Override
    public int getCount() {
        return mData == null ? 0 : mData.size();
    }

    @Override
    public String getItem(int i) {
        if (mData != null && i < mData.size()) {
            return mData.get(i);
        }
        return null;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        Component view;
        ViewHolder viewHolder = null;
        if (component == null) {
            view = LayoutScatter.getInstance(componentContainer.getContext()).parse(
                    ResourceTable.Layout_items_recyclerview, null, false);
            viewHolder = new ViewHolder(view);
            view.setTag(viewHolder);
        } else {
            view = component;
            Object tag = view.getTag();
            if (tag instanceof ViewHolder) {
                viewHolder = (ViewHolder) tag;
            }
        }
        if (viewHolder != null) {
            viewHolder.text.setText(getItem(i));
        }
        return view;
    }

    /**
     * 设置新数据
     *
     * @param list 新的数据list
     */
    public void setNewData(List<String> list) {
        this.mData = (list == null ? new ArrayList<String>() : list);
        this.notifyDataChanged();
    }

    /**
     * 获取列表list
     *
     * @return List
     */
    public List<String> getData() {
        return this.mData;
    }


    /**
     * Holder 复用
     */
    private static class ViewHolder {
        /**
         * text 控件
         */
        private Text text;

        /**
         * constructor
         *
         * @param view root view
         */
        public ViewHolder(Component view) {
            text = (Text) view.findComponentById(ResourceTable.Id_text);
        }
    }
}
